// ignore_for_file: must_be_immutable

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:orginone/components/XImage/XImage.dart';
import 'package:orginone/config/theme/UIConfig.dart';
import 'package:orginone/config/theme/unified_style.dart';
import 'package:orginone/dart/core/thing/standard/application.dart';
import 'package:orginone/dart/core/thing/standard/form.dart' as form1;
import 'package:orginone/dart/core/work/index.dart';
import 'package:orginone/routers/pages.dart';

class AssetsTypePage extends StatefulWidget {
  AssetsTypePage({Key? key, this.typeData}) : super(key: key);
  IApplication? typeData;

  @override
  State<AssetsTypePage> createState() => _AssetsTypePageState();
}

class _AssetsTypePageState extends State<AssetsTypePage> {
  late IApplication data;

  ///办事or表单
  int selectThingOrExcel = 0;

  List<form1.IForm> allIform = <form1.IForm>[];
  List<IWork> allIwork = <IWork>[];
  //应用类型
  List<IApplication> listOperation = [];
  String selectOperationId = "";

  @override
  void initState() {
    super.initState();
    data = widget.typeData!;
    initChildrenData();
  }

  initChildrenData() async {
    allIform = await data.loadAllForms();
    allIwork = await data.loaAlldWorks();
    listOperation.add(data);
    listOperation.addAll(data.children);
    selectOperationId = data.id;
    if (mounted) {
      setState(() {});
    }
  }

  Widget getClickButton(String text, double width, Function? onClick,
      {double? height,
      double? borderRadius,
      FontWeight? fontWeight,
      Color? color,
      Color? textColor,
      double? textSize,
      double? borderWidth,
      EdgeInsetsGeometry? padding,
      EdgeInsetsGeometry? margin,
      Color? borderColor}) {
    return GestureDetector(
        onTap: onClick as void Function()?,
        child: Container(
          width: width,
          height: height ?? 45.0,
          alignment: Alignment.center,
          padding: padding ?? const EdgeInsets.fromLTRB(0, 8, 0, 8),
          margin: margin ?? const EdgeInsets.all(0),
          decoration: BoxDecoration(
            color: color ?? const Color(0xffFDDF0D),
            borderRadius: BorderRadius.circular((borderRadius ?? 10)),
            border: Border.all(
                width: borderWidth ?? 1,
                color: borderColor ?? (color ?? const Color(0xffFDDF0D))),
          ),
          child: Text(text,
              style: TextStyle(
                fontFamily: "PingFang SC",
                decoration: TextDecoration.none,
                color: textColor ?? Colors.black,
                fontSize: textSize ?? 16,
                fontWeight: fontWeight ?? FontWeight.w400,
              )),
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
          border: Border(
              bottom: BorderSide(color: XColors.dividerLineColor, width: 1))),
      width: UIConfig.screenWidth,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: const EdgeInsets.all(16),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(data.name, style: XFonts.size24Black0W700),
                Container(
                    height: 25,
                    decoration: const BoxDecoration(
                        color: XColors.dividerLineColor,
                        borderRadius: BorderRadius.all(Radius.circular(4))),
                    child: Row(
                      children: [
                        getClickButton("办事", 48, () {
                          setState(() {
                            selectThingOrExcel = 0;
                          });
                        },
                            height: 25,
                            padding: const EdgeInsets.only(top: 2, bottom: 2),
                            color: selectThingOrExcel == 0
                                ? XColors.selectedColor
                                : XColors.transparent,
                            borderRadius: 4,
                            textSize: 18.sp,
                            textColor: selectThingOrExcel == 0
                                ? XColors.white
                                : XColors.doorDesGrey),
                        getClickButton("表单", 48, () {
                          setState(() {
                            selectThingOrExcel = 1;
                          });
                        },
                            height: 25,
                            textSize: 18.sp,
                            padding: const EdgeInsets.only(top: 2, bottom: 2),
                            color: selectThingOrExcel == 1
                                ? XColors.selectedColor
                                : XColors.transparent,
                            borderRadius: 4,
                            textColor: selectThingOrExcel == 1
                                ? XColors.white
                                : XColors.doorDesGrey),
                      ],
                    ))
              ],
            ),
          ),
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: buildRowSelectList(),
            ),
          ),
          data.id == selectOperationId
              ? buildItemApp(
                  context, selectThingOrExcel == 0 ? allIwork : allIform)
              : buildItemApp(
                  context,
                  selectThingOrExcel == 0
                      ? allIwork
                          .where((element) =>
                              element.superior.id == selectOperationId)
                          .toList()
                      : allIform
                          .where((element) =>
                              element.superior.id == selectOperationId)
                          .toList())
        ],
      ),
    );
  }

  buildRowSelectList() {
    return listOperation
        .asMap()
        .keys
        .map((index) => GestureDetector(
              onTap: () {
                setState(() {
                  selectOperationId = listOperation[index].id;
                });
              },
              child: Container(
                  width: 90,
                  decoration: BoxDecoration(
                      color: selectOperationId == listOperation[index].id
                          ? const Color(0xfff2f3ff)
                          : XColors.dividerLineColor,
                      borderRadius: const BorderRadius.all(Radius.circular(4))),
                  margin: const EdgeInsets.all(2),
                  padding: const EdgeInsets.fromLTRB(8, 4, 8, 4),
                  child: Text(
                      listOperation[index].name == data.name
                          ? "全部"
                          : listOperation[index].name,
                      textAlign: TextAlign.center,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color: selectOperationId == listOperation[index].id
                            ? const Color(0xff366ef4)
                            : const Color(0xff424a57),
                        fontSize: 14,
                        fontWeight: selectOperationId == listOperation[index].id
                            ? FontWeight.w600
                            : FontWeight.w400,
                      ))),
            ))
        .toList();
  }
}

buildItemApp(BuildContext context, List<dynamic> list) {
  return GridView.count(
      physics: const NeverScrollableScrollPhysics(),
      padding: const EdgeInsets.only(top: 16),
      shrinkWrap: true,
      crossAxisCount: 4,
      childAspectRatio: 1.1,
      children: list.map<Widget>((e) => renderCmdBtn(context, e)).toList());
}

renderCmdBtn(BuildContext context, dynamic file) {
  return GestureDetector(
    onTap: () async {
      if (file is IWork) {
        RoutePages.jumpNewWork(work: file);
      } else if (file is form1.IForm) {
        // form1.Form form = await FormTool.loadForm(file);
        // form.metadata.showAttributes = true;
        // RoutePages.jumpFormPage(form);
        RoutePages.jumpStore(context, parentData: file);
      }
    },
    child: SizedBox(
      width: 120.w,
      child: Column(
        children: [
          XImage.entityIcon(file, width: 60.w),
          Container(
            margin: EdgeInsets.only(top: 16.h),
            child: SizedBox(
              height: 16,
              child: Text(
                file.name,
                // softWrap: true,
                maxLines: 1,
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: XColors.doorDesGrey,
                  fontSize: 18.sp,
                  fontFamily: 'PingFang SC',
                  // height: 0.16,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ),
          ),
        ],
      ),
    ),
  );
}
